import 'dart:ui';
import 'package:magic_car/authinspcter/authinspectorchargerrec.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/jiance/jiance_detail.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/user/group_use_record.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
//import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class BussinessGroupRecPage extends StatefulWidget {
  BussinessGroupRecPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<BussinessGroupRecPage> {
  ScrollController _scrollController = new ScrollController();
  List formList;
  List items = [
    {
      'title': '月份',
      'select': false,
      'value': '',
      'code': 'online',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '类型',
      'select': false,
      'value': '',
      'code': 'online',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
  ];
  int page = 1;
  String MIN_DATETIME = '1900-01-01';
  String MAX_DATETIME = '2025-01-01';
  String INIT_DATETIME = '2020-05-01';
  String _format = 'yyyy-MMMM';
  List Inspector = [];

  DateTime _dateTime;
  ScrollController _controller = new ScrollController();

  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;
//DateTimePickerLocale _locale = Locale('zn');
  List<DateTimePickerLocale> _locales = DateTimePickerLocale.values;

  String defalut_date = "日期";
  bool selectdate = false;

  String defalut_type = "检测收益";
  bool selecttype = true;
  String defalt_type_value = "0";

  String total_money = "0.00";

  bool _saving = false;

  initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        loadMore();
      }
    });
    formList = [];
    loaddata();
  }

//加载更多数据
  loadMore() {
    loaddata();
  }

  //加载数据
  loaddata() async {
    setState(() {
      _saving = true;
    });
    //  LoadingPage loadpage = LoadingPage(context);
    //   loadpage.show();
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    if (selectdate == true) {
      map['month'] = defalut_date;
    } else {
      map['month'] = "";
    }
    map['type'] = defalt_type_value;
    map['page'] = page.toString();
    String role = pref.getString('role');
    if (role != "1") {
      map["bussiness"] = "1";
    }

    print(map);
    if (page == 1) formList = [];

    HttpHelper.post(HttpHelper.API_Bussinessgrouprec, (data) async {
      setState(() {
        _saving = false;
      });
      //loadpage.close();
      if (data != null) {
        print(data);

        if (data["code"].toString() == "1") {
          setState(() {
            formList.addAll(data["info"]);
            // total_money = data['info']['total'] != null
            //     ? data['info']['total'].toString()
            //     : "0.00";
            //formList = data["info"];
            // acountinfo = data["info"];
          });
          if (data["info"].length > 0) {
            page++;
          }
        }
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in formList) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
              color: Colors.white,
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                   
                    // Navigator.of(context)
                    //     .push(new MaterialPageRoute(builder: (_) {
                    //   return new JIanceDetailPage(item["order_id"].toString());
                    // }));
                     Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (_) {
                      return new GroupusePage(item["id"].toString());
                    }));
                    //  Navigator.of(context)
                    //     .push(new MaterialPageRoute(builder: (_) {
                     //  return new AuthchargerOrderRecPage(item["id"].toString());
                    // }));
                  },
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Padding(
                            padding: new EdgeInsets.fromLTRB(15, 10, 10, 10),
                            child: new Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                new Padding(
                                  padding:
                                      new EdgeInsets.fromLTRB(0, 10, 0, 10),
                                  child: Text(
                                    item['add_time'],
                                    style: TextStyle(
                                        fontSize: 12,
                                        color: Color.fromRGBO(82, 82, 82, 1)),
                                  ),
                                ),
                                Text(
                                  "总计：" + item['money'].toString() + "",
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Color.fromRGBO(64, 64, 64, 1)),
                                ),
                                // Text(
                                //   "已用：" + item['used_num'].toString() + "台",
                                //   style: TextStyle(
                                //       fontSize: 14,
                                //       color: Color.fromRGBO(64, 64, 64, 1)),
                                // ),
                                Text(
                                  "余额：" + item['balance'].toString() + "",
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Color.fromRGBO(64, 64, 64, 1)),
                                ),
                                // new Padding(
                                // padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
                                // child: Text('2019.10.22',style: TextStyle(fontSize:12,color: Color.fromRGBO(143, 143, 143, 1) ),),
                                // )
                              ],
                            )),
                        flex: 1,
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                          child: new Text(
                            item['money'],
                            style: TextStyle(
                                fontSize: 18,
                                color: Color.fromRGBO(27, 182, 251, 1)),
                          )),
                    ],
                  )))));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  void _showDatePicker(item) {
    print('选择日期');
    DatePicker.showDatePicker(
      context,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('不限', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onClose: () => print("----- onClose -----"),
      onCancel: () {
        //不限
        setState(() {
          defalut_date = '月份';
          selectdate = false;
        });
        page = 1;
        loaddata();
      },
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          //_dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        print(item);
        setState(() {
          defalut_date = formatDate(dateTime, [yyyy, "-", mm]);
          selectdate = true;
        });

        page = 1;
        loaddata();
        //saveResult();
      },
    );
  }

  Widget filterBtn() {
    var view = Padding(
        padding: new EdgeInsets.fromLTRB(5, 5, 0, 5),
        child: new Row(children: <Widget>[
          GestureDetector(
              // key: _myKey,
              onTap: () {
                _showDatePicker(items);
              },
              child: Container(
                width: 100,
                padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                child: Center(
                    child: Text(
                  defalut_date,
                  style: new TextStyle(
                      fontSize: 10,
                      color: selectdate == false
                          ? Color.fromRGBO(120, 120, 120, 1)
                          : Colors.white),
                )),
                decoration: new BoxDecoration(
                  color: selectdate == false
                      ? Color.fromRGBO(205, 205, 205, 1)
                      : Colors.blue,
                  borderRadius: new BorderRadius.all(new Radius.circular(6.0)),
                ),
              )),
          Padding(
              padding: new EdgeInsets.fromLTRB(8, 0, 0, 0),
              child: GestureDetector(
                  // key: _myKey,
                  onTap: () {
                    _selecttype();
                  },
                  child: Container(
                    width: 80,
                    padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                    child: Center(
                        child: Text(
                      defalut_type,
                      style: new TextStyle(
                          fontSize: 10,
                          color: selecttype == false
                              ? Color.fromRGBO(120, 120, 120, 1)
                              : Colors.white),
                    )),
                    decoration: new BoxDecoration(
                      color: selecttype == false
                          ? Color.fromRGBO(205, 205, 205, 1)
                          : Colors.blue,
                      borderRadius:
                          new BorderRadius.all(new Radius.circular(6.0)),
                    ),
                  ))),
          Padding(
            padding: new EdgeInsets.fromLTRB(8, 0, 0, 0),
            child: Text(
              '总计：¥ ' + total_money,
              style: TextStyle(fontSize: 12),
            ),
          )
        ]));
    return view;
  }

  _selecttype() async {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 180,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            //connect();
                          },
                          child: Center(
                              child: Text('选择收益类型',
                                  style: TextStyle(fontSize: 16))))),
                  // new Container(
                  //     decoration: new BoxDecoration(
                  //         border: Border(
                  //             bottom: BorderSide(
                  //                 width: 1, color: Color(0xffe5e5e5)))),
                  //     height: 50,
                  //     child: new GestureDetector(
                  //         behavior: HitTestBehavior.opaque,
                  //         onTap: () async {
                  //           Navigator.pop(context);
                  //           setState(() {
                  //             defalut_type = "类型";
                  //             selecttype = false;
                  //             defalt_type_value = "";
                  //           });
                  //           page = 1;
                  //           loaddata();
                  //           //connect();
                  //         },
                  //         child: Center(
                  //             child: Text('全部类型',
                  //                 style: TextStyle(fontSize: 16))))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            //connect();
                            setState(() {
                              defalut_type = "检测收益";
                              selecttype = true;
                              defalt_type_value = "0";
                            });
                            page = 1;
                            loaddata();
                          },
                          child: Center(
                              child: Text('检测收益',
                                  style: TextStyle(
                                    fontSize: 16,
                                  ))))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            setState(() {
                              defalut_type = "渠道收益";
                              selecttype = true;
                              defalt_type_value = "1";
                            });
                            page = 1;
                            loaddata();
                          },
                          child: Center(
                              child: Text('渠道收益',
                                  style: TextStyle(fontSize: 16))))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            setState(() {
                              defalut_type = "任务收益";
                              selecttype = true;
                              defalt_type_value = "2";
                            });
                            page = 1;
                            loaddata();
                            //connect();
                          },
                          child: Center(
                              child: Text('任务收益',
                                  style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
          title: new Text('套餐充值记录',style: TextStyle(fontSize: Config.title_size),),
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: ModalProgressHUD(
            // color: Colors.blue,
            inAsyncCall: _saving,
            child: new Center(
                child: Container(
              decoration: new BoxDecoration(
                color: Colours.base_page_color,
              ),
              child: Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Stack(children: <Widget>[
                    // Align(
                    //     alignment: Alignment.topLeft,
                    //     child: Padding(
                    //         padding: new EdgeInsets.fromLTRB(10, 10, 10, 5),
                    //         child: new Container(
                    //             child: new Column(
                    //                 mainAxisAlignment: MainAxisAlignment.start,
                    //                 crossAxisAlignment:
                    //                     CrossAxisAlignment.start,
                    //                 children: <Widget>[
                    //               new Container(
                    //                 child: filterBtn(),
                    //               )
                    //             ])))),
                    Align(
                        alignment: Alignment.bottomCenter,
                        child: Padding(
                            padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
                            child: formList.length == 0
                                ? Nodata()
                                : new ListView(
                                    children: <Widget>[buildcontent()],
                                    controller: _scrollController,
                                  )))
                  ])
                  //  new ListView(
                  //   children: <Widget>[buildcontent()],
                  // )
                  ),
            ))));
  }
}
